<template>
  <el-dialog
    :visible.sync="showModal"
    :close-on-click-modal="dialog.click"
    :close-on-press-escape="dialog.esc"
    :show-close="dialog.closeBtn"
    :title="dialog.title"
    center
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
      <el-form-item label="" prop="newAuth">
        <el-input v-model="ruleForm.newAuth" :type="passwordType" placeholder="输入新密码" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-form-item label="" prop="newAuthAgain">
        <el-input v-model="ruleForm.newAuthAgain" :type="passwordType" placeholder="确认新密码" />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <p style="color:red;">提示：修改完需要重新登录</p>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import md5 from 'md5';
import { mapActions } from 'vuex';

import { forceResetPwd } from '@/api/admin/user';
import rules from '@/utils/rules.js';

export default {
  name: 'App',
  props: {
    showModal: {
      type: Boolean
    }
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.newAuth) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      passwordType: 'password',
      dialog: {
        title: '修改密码',
        showModal: false,
        click: false,
        esc: false,
        closeBtn: false
      },
      ruleForm: {
        newAuth: '',
        newAuthAgain: ''
      },
      rules: {
        newAuth: [
          { required: true, validator: rules.validatePassword, trigger: 'blur' }
        ],
        newAuthAgain: [
          { required: true, validator: validatePass2, trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    ...mapActions([
      'LogOut'
    ]),
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          forceResetPwd(md5(this.ruleForm.newAuth)).then(res => {
            this.LogOut().then(() => {
              this.$router.push({
                name: 'login'
              });
            });
          });
        }
      });
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.show-pwd{
  position: absolute;
  right: 20px;
}
</style>
